<template>
  <div class="menu-editor">
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      label-position="left"
    >
      <el-form-item label="菜单名称" prop="name">
        <el-input
          v-model="form.name"
          placeholder="请输入菜单名称"
          clearable
        />
      </el-form-item>

      <el-form-item label="菜单路径" prop="path">
        <el-input
          v-model="form.path"
          placeholder="请输入菜单路径"
          clearable
        />
        <div class="form-tip">
          修改路径可能会影响现有的路由配置
        </div>
      </el-form-item>

      <el-form-item label="选择图标" prop="icon">
        <div class="icon-selector">
          <el-input
            v-model="form.icon"
            placeholder="选择图标"
            readonly
            class="icon-input"
          >
            <template #prefix>
              <i v-if="form.icon" :class="form.icon" class="selected-icon"></i>
            </template>
            <template #suffix>
              <el-button text @click="showIconDialog = true">
                <i class="fa fa-search"></i>
              </el-button>
            </template>
          </el-input>
        </div>
      </el-form-item>

      <el-form-item label="父菜单" prop="parent_id">
        <el-select
          v-model="form.parent_id"
          placeholder="选择父菜单"
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="option in availableParents"
            :key="option.id"
            :label="option.name"
            :value="option.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="组件名称" prop="component_name">
        <el-input
          v-model="form.component_name"
          placeholder="Vue组件名称"
          clearable
        />
        <div class="form-tip">
          用于前端路由的组件名称
        </div>
      </el-form-item>

      <el-form-item label="权限代码" prop="permission_code">
        <el-input
          v-model="form.permission_code"
          placeholder="权限控制代码"
          clearable
        />
      </el-form-item>

      <el-form-item label="菜单描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="3"
          placeholder="请输入菜单功能描述"
        />
      </el-form-item>

      <el-form-item label="排序权重" prop="sort_weight">
        <el-input-number
          v-model="form.sort_weight"
          :min="0"
          :max="9999"
          :step="1"
          style="width: 100%"
        />
        <div class="form-tip">
          数值越小排序越靠前
        </div>
      </el-form-item>

      <el-form-item label="状态设置">
        <el-switch
          v-model="form.is_enabled"
          active-text="启用"
          inactive-text="禁用"
        />
      </el-form-item>

      <el-form-item v-if="form.is_generated" label="自动生成">
        <el-tag type="success">此菜单为系统自动生成</el-tag>
      </el-form-item>
    </el-form>

    <div class="dialog-footer">
      <el-button @click="$emit('cancel')">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitting">
        保存修改
      </el-button>
    </div>

    <!-- 图标选择对话框 -->
    <el-dialog
      v-model="showIconDialog"
      title="选择图标"
      width="800px"
      :append-to-body="true"
    >
      <IconSelector
        :selected="form.icon"
        @select="handleIconSelect"
        @close="showIconDialog = false"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElForm } from 'element-plus'
import IconSelector from './IconSelector.vue'
import { dynamicMenuApi } from '@/api/dynamicMenu'

// Props
interface Props {
  menu: any
  parentOptions: Array<{ id: any; name: string }>
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  success: []
  cancel: []
}>()

// 响应式数据
const formRef = ref<InstanceType<typeof ElForm>>()
const showIconDialog = ref(false)
const submitting = ref(false)

const form = reactive({
  name: '',
  path: '',
  icon: '',
  parent_id: null,
  component_name: '',
  permission_code: '',
  description: '',
  sort_weight: 0,
  is_enabled: true,
  is_generated: false
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' },
    { min: 2, max: 20, message: '菜单名称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  path: [
    { required: true, message: '请输入菜单路径', trigger: 'blur' },
    { pattern: /^\//, message: '路径必须以 / 开头', trigger: 'blur' }
  ],
  icon: [
    { required: true, message: '请选择图标', trigger: 'change' }
  ],
  sort_weight: [
    { required: true, message: '请输入排序权重', trigger: 'blur' },
    { type: 'number', min: 0, max: 9999, message: '排序权重必须在 0-9999 之间', trigger: 'blur' }
  ]
}

// 计算属性
const availableParents = computed(() => {
  // 过滤掉自己和自己的子菜单，避免循环引用
  return props.parentOptions.filter(option => {
    if (option.id === props.menu.id) return false
    // 这里可以添加更复杂的逻辑来检查是否是子菜单
    return true
  })
})

// 方法
const handleIconSelect = (icon: string) => {
  form.icon = icon
  showIconDialog.value = false
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    const valid = await formRef.value.validate()
    if (!valid) return
    
    submitting.value = true
    
    // 构建更新数据
    const updateData = {
      name: form.name,
      path: form.path,
      icon: form.icon,
      parent_id: form.parent_id,
      component_name: form.component_name,
      permission_code: form.permission_code,
      description: form.description,
      sort_weight: form.sort_weight,
      is_enabled: form.is_enabled
    }
    
    const response = await dynamicMenuApi.updateMenu(props.menu.id, updateData)
    
    if (response.success) {
      ElMessage.success('菜单更新成功！')
      emit('success')
    } else {
      ElMessage.error(response.message || '更新菜单失败')
    }
  } catch (error) {
    console.error('更新菜单失败:', error)
    ElMessage.error('更新菜单失败')
  } finally {
    submitting.value = false
  }
}

const initForm = () => {
  Object.assign(form, {
    name: props.menu.name || '',
    path: props.menu.path || '',
    icon: props.menu.icon || '',
    parent_id: props.menu.parent_id || null,
    component_name: props.menu.component_name || '',
    permission_code: props.menu.permission_code || '',
    description: props.menu.description || '',
    sort_weight: props.menu.sort_weight || 0,
    is_enabled: props.menu.is_enabled !== false,
    is_generated: props.menu.is_generated || false
  })
}

// 生命周期
onMounted(() => {
  initForm()
})
</script>

<style lang="scss" scoped>
.menu-editor {
  .form-tip {
    font-size: 12px;
    color: rgba(255, 255, 255, 0.6);
    margin-top: 4px;
  }
  
  .icon-selector {
    .icon-input {
      .selected-icon {
        color: #00eaff;
        font-size: 16px;
      }
    }
  }
  
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    margin-top: 24px;
    padding-top: 16px;
    border-top: 1px solid rgba(255, 255, 255, 0.1);
  }
}

// Element Plus 样式覆盖
:deep(.el-form-item__label) {
  color: rgba(255, 255, 255, 0.9);
}

:deep(.el-input__inner) {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: #fff;
  
  &::placeholder {
    color: rgba(255, 255, 255, 0.5);
  }
}

:deep(.el-textarea__inner) {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: #fff;
  
  &::placeholder {
    color: rgba(255, 255, 255, 0.5);
  }
}

:deep(.el-select) {
  .el-input__inner {
    background: rgba(255, 255, 255, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.2);
    color: #fff;
  }
}

:deep(.el-input-number) {
  .el-input__inner {
    background: rgba(255, 255, 255, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.2);
    color: #fff;
  }
}

:deep(.el-switch) {
  .el-switch__label {
    color: rgba(255, 255, 255, 0.8);
    
    &.is-active {
      color: #00eaff;
    }
  }
}

:deep(.el-button) {
  &.el-button--primary {
    background: linear-gradient(135deg, #00eaff, #0099cc);
    border: none;
    
    &:hover {
      background: linear-gradient(135deg, #00d4e6, #0088bb);
    }
  }
}

:deep(.el-tag) {
  &.el-tag--success {
    background: rgba(103, 194, 58, 0.2);
    border-color: rgba(103, 194, 58, 0.5);
    color: #67c23a;
  }
}
</style>
